package com.longcai.service.impl.customer;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.longcai.bean.ApiResult;
import com.longcai.constants.BaseConstants;
import com.longcai.constants.DicConstants;
import com.longcai.entity.customer.ClyjUser;
import com.longcai.entity.customer.ClyjUserProperty;
import com.longcai.entity.customer.ClyjUserSign;
import com.longcai.entity.sys.ClyjDict;
import com.longcai.mapper.customer.ClyjUserMapper;
import com.longcai.mapper.customer.ClyjUserPropertyMapper;
import com.longcai.mapper.customer.ClyjUserSignMapper;
import com.longcai.service.customer.ClyjUserPropertyService;
import com.longcai.service.customer.ClyjUserSignService;
import com.longcai.service.dict.ClyjDictService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 用户签到表 服务实现类
 * </p>
 *
 * @author M
 * @since 2019-04-01
 */
@Service
public class ClyjUserSignServiceImpl extends ServiceImpl<ClyjUserSignMapper, ClyjUserSign> implements ClyjUserSignService {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ClyjUserSignMapper clyjUserSignMapper;
    @Autowired
    private ClyjUserPropertyMapper clyjUserPropertyMapper;
    @Autowired
    private ClyjUserPropertyService clyjUserPropertyService;
    @Autowired
    private ClyjUserMapper clyjUserMapper;
    @Autowired
    private ClyjDictService clyjDictService;

    /**
     * 用户签到
     *
     * @param id
     * @param day
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ApiResult getUserSign(String id, String day) {
        try {
            //查找用户
            QueryWrapper<ClyjUser> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("user_id", id);
            ClyjUser clyjUser = this.clyjUserMapper.selectOne(queryWrapper1);
            //新增签到表
            ClyjUserSign clyjUserSign = new ClyjUserSign();
            clyjUserSign.setId(UUID.randomUUID().toString().replace("-", ""));
            clyjUserSign.setUserId(id);
            int days = Integer.parseInt(day);
            QueryWrapper<ClyjUserProperty> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", id);
            ClyjUserProperty clyjUserProperty = this.clyjUserPropertyMapper.selectOne(queryWrapper);
            //判断是否签到7天
            if (days == 7) {
                ClyjDict clyjDict = clyjDictService.gerByTypeCode(DicConstants.SIGN_SEEVENDAY_POCKET);
                if (clyjDict == null) {
                    logger.error("连续七日签到零钱未配置");
                }
                /**资金变动（红包，零钱，积分）TODO_HYF**/
                ApiResult<?> r = clyjUserPropertyService.changeFinance(id, new BigDecimal(clyjDict.getAttname()), "0", DicConstants.SIGN_SEEVENDAY_POCKET, "0", null, BaseConstants.UNFREEZE,null);
                if (!r.getCode().equals("success")) {
                    return r;
                }
            } else {
                ClyjDict clyjDict = clyjDictService.gerByTypeCode(DicConstants.SIGN_EVERYDAY_POCKET);
                if (clyjDict == null) {
                    logger.error("连续七日签到零钱未配置");
                }
                /**资金变动（红包，零钱，积分）TODO_HYF**/
                ApiResult<?> r = clyjUserPropertyService.changeFinance(id, new BigDecimal(clyjDict.getAttname()), "0", DicConstants.SIGN_EVERYDAY_POCKET, "0", null, BaseConstants.UNFREEZE,null);
                if (!r.getCode().equals("success")) {
                    return r;
                }
            }
            clyjUserSign.setDay(days);
            clyjUserSign.setCheckIn(days);
            clyjUserSign.setCreateTime(new Date());
            Integer integer = this.clyjUserSignMapper.insert(clyjUserSign);
            logger.debug("签到成功", integer);
            return ApiResult.success(integer);
        } catch (Exception e) {
            logger.error("签到失败");
            e.printStackTrace();
            return ApiResult.fail("签到失败" + e.getMessage());
        }
    }

    /**
     * 用户签到明细
     *
     * @param id
     * @return
     */
    @Override
    public ApiResult getSignList(String id) {
        try {
            List clyjUserSignList = this.clyjUserSignMapper.select(id);
            logger.debug("查询成功++++++++++", clyjUserSignList);
            return ApiResult.success(clyjUserSignList);
        } catch (Exception e) {
            logger.error("查询失败");
            e.printStackTrace();
            return ApiResult.fail("查询失败" + e.getMessage());
        }
    }

    /**
     * 获取签到天数
     *
     * @param id
     * @param date1
     * @param date2
     * @return
     */
    @Override
    public Map<String, Object> getSignDay(String id, String date1, String date2) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            //根据今天日期查询是否已签到和已签到天数
            QueryWrapper<ClyjUserSign> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("create_time", date1);
            ClyjUserSign clyjUserSign = this.clyjUserSignMapper.selectOne(queryWrapper);
            //判断今天是否签到，未签到查询前一天
            if (clyjUserSign == null) {
                QueryWrapper<ClyjUserSign> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.like("create_time", date2);
                ClyjUserSign clyjUserSign1 = this.clyjUserSignMapper.selectOne(queryWrapper1);
                resultMap.put("code", "success");
                resultMap.put("flag", 0);
                //如果前一天为空 说明已签到为0
                if (clyjUserSign1 == null) {
                    resultMap.put("data", 0);
                } else {
                    resultMap.put("data", clyjUserSign1.getCheckIn());
                }
            } else {
                resultMap.put("code", "success");
                resultMap.put("flag", 1);
                resultMap.put("data", clyjUserSign.getCheckIn());
            }
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("errorMsg", e.getMessage());
            return resultMap;
        }
    }
}
